package cmd;

import tree.LeafMsg;
import tree.Tress;
import view.ViewTress;
import tree.Root;

class Root_Cmd extends Tress {
    static var max_szie = 200;
    //环形数组 若一帧加的命令大于max_size 会有问题
    var cmds : Array<Cmd>;
    //命令回撤的下限
    var start = 0;
    //命令执行的上限
    var end = 0;
    var current = 0;

    public function new() {
        super();
        cmds = new Array<Cmd>();
        cmds.resize(max_szie);
    }

    public function AddCmd(cmd) {
        cmds[end] = cmd;
        end = (end + 1) % max_szie;
        if(end == current){
            trace("未执行的命令过多!! 增加max_size");
        }
        if(end == start){
            start++;
        }        
    }
    //执行 -1表示执行到底
    public function Do(step) {
        while (step != 0 && current != end){
            step --;
            cmds[current].OnEnter(null);
            current = (current + 1) % max_szie;
        }
    }

    //撤销
    public function Undo(step) {
        while (step != 0 && current != start){
            step--;
            current = (current - 1 + max_szie) % max_szie; 
            cmds[current].OnExit(null);
        }
        end = current;
    }

    public override function OnUpdate(msg:LeafMsg) {
        super.OnUpdate(msg);
        var isDo = true;
        if(msg != null){
            switch msg {
                case Undo:
                    isDo = false;
                default:
            }
        }
        if (isDo) {
            Do(-1);
        }
        else {
            Undo(1);
        }
    }

}